package com.example.demo.controller;

import com.example.demo.annotation.Authorization;
import com.example.demo.annotation.CurrentUser;
import com.example.demo.controller.dto.UserAuthDTO;
import com.example.demo.controller.dto.UserDTO;
import com.example.demo.core.Result;
import com.example.demo.model.User;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by xdkxlk on 2017/8/11.
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<UserAuthDTO> login(@RequestBody User userData) {
        User user = userService.getByName(userData.getName());
        if (user == null) {
            return Result.fail("用户名不存在");
        }
        if (!user.getPassword().equals(userData.getPassword())) {
            return Result.fail("用户密码不正确");
        }

        UserAuthDTO userAuthDTO = UserAuthDTO.convertFor(user);
        userAuthDTO.setToken(tokenService.createToken(user));
        return Result.success(userAuthDTO);
    }

    @Authorization
    @RequestMapping(value = "", method = RequestMethod.GET)
    public Result<UserDTO> getPersonInfo(@CurrentUser User userData) {
        User user = userService.getByName(userData.getName());
        return Result.success(UserDTO.convertFor(user));
    }
}
